import React, { ReactNode } from 'react';
import BookMarkCard from '@/components/bookmark-card';
import bookmarkStyle from './index.less';
import Bookmark from '@/api/model/bookmark';
import { BackTop, Empty, Nav, SideSheet } from '@douyinfe/semi-ui';
import {
  IllustrationNoResult,
  IllustrationNoResultDark,
} from '@douyinfe/semi-illustrations';
import { NavItems } from '@douyinfe/semi-ui/lib/es/navigation';
import * as Icons from '@douyinfe/semi-icons';

export default class IndexPage extends React.Component {
  constructor(props: any) {
    super(props);
    this.state = {
      bookmark: [],
      bookmarkTypeList: {},
      isShowMobile: false,
    };
    this.getBookmarkList().then();
    this.getBookmarkList = this.getBookmarkList.bind(this);
    this.changeIsShowMobile = this.changeIsShowMobile.bind(this);
  }

  async componentsWillMount() {
    await this.getBookmarkList();
  }

  componentDidMount() {}

  async getBookmarkList(category_id?: any) {
    console.log('Icons', Icons);
    console.log("Icons['IconBookmark']", Icons['IconBookmark']);
    const data = { category_id };
    if (category_id == 0) delete data.category_id;
    const res = await Bookmark.BookmarkUser();
    this.setState({
      bookmark: res.data,
    });
  }

  changeIsShowMobile() {
    const { isShowMobile }: any = this.state;
    this.setState({
      isShowMobile: !isShowMobile,
    });
  }

  render() {
    const { bookmark, isShowMobile }: any = this.state;
    const emptyStyle = {
      padding: 30,
    };
    return (
      <div className={[bookmarkStyle.bookmark_container].join(' ')}>
        <Navbar
          changeIsShowMobile={this.changeIsShowMobile}
          bookmark={bookmark}
          isShowMobile={isShowMobile}
        />
        <h3 className={bookmarkStyle.anchor} />
        <div className={bookmarkStyle.bookmark_content}>
          {bookmark.length !== 0 ? (
            bookmark.map((item: any, index: React.Key | null | undefined) => {
              if (item.bookmark.length === 0) return;
              return (
                <div key={index}>
                  <h3 className={bookmarkStyle.anchor} id={item.category_name}>
                    {item.category_name}
                  </h3>
                  <div className={bookmarkStyle.bookmark_cards}>
                    {item.bookmark.map(
                      (
                        bookmarkItem: any,
                        bookmarkIndex: React.Key | null | undefined,
                      ) => {
                        return (
                          <div
                            key={bookmarkIndex}
                            className={bookmarkStyle.bookmark_card}
                          >
                            <BookMarkCard bookmarkItem={bookmarkItem} />
                          </div>
                        );
                      },
                    )}
                  </div>
                </div>
              );
            })
          ) : (
            <Empty
              image={
                <IllustrationNoResult style={{ width: 150, height: 150 }} />
              }
              darkModeImage={
                <IllustrationNoResultDark style={{ width: 150, height: 150 }} />
              }
              description={'搜索无结果'}
              style={emptyStyle}
            />
          )}
        </div>
        <BackTop />
        <div className={bookmarkStyle.mobileIcon}>
          <Icons.IconBookmark
            onClick={this.changeIsShowMobile}
            style={{ fontSize: '1.8rem', color: 'var(--semi-color-text-0)' }}
          />
        </div>
      </div>
    );
  }
}

const Navbar = (props: {
  bookmark: any;
  isShowMobile: boolean;
  changeIsShowMobile: any;
}) => {
  const { bookmark, isShowMobile, changeIsShowMobile } = props;
  const newBookmark:
    | NavItems
    | { itemKey: any; text: any; icon: ReactNode }[]
    | undefined = [];
  bookmark.forEach(
    (t: {
      bookmark: any;
      category_id: any;
      category_name: any;
      icon: string;
    }) => {
      const iconString: string = t.icon;
      if (t.bookmark.length !== 0) {
        newBookmark.push({
          itemKey: t.category_id,
          text: t.category_name,
          icon: iconString
            ? // @ts-ignore
              React.createElement(Icons[iconString], null, 123)
            : '',
        });
      }
    },
  );
  console.log('newBookmark', newBookmark);
  const scrollToAnchor = (anchorName: any) => {
    if (anchorName) {
      // 找到锚点
      let anchorElement = document.getElementById(anchorName);
      // 如果对应id的锚点存在，就跳转到锚点
      if (anchorElement) {
        anchorElement.scrollIntoView({
          block: 'start',
          inline: 'center',
          behavior: 'smooth',
        });
      }
    }
  };

  let mediaQuery = window.matchMedia('(max-width: 576px)');
  const maskStyle = {
    backdropFilter: 'blur(5px)',
  };
  return (
    <div className={bookmarkStyle.nav_bar}>
      <Nav
        style={{ height: '100%' }}
        bodyStyle={{ height: '100%' }}
        defaultOpenKeys={['job', 'resource']}
        items={newBookmark}
        onSelect={(key) => {
          scrollToAnchor(key.selectedItems[0].text);
        }}
        footer={{
          collapseButton: !mediaQuery.matches,
        }}
      />
      <SideSheet
        bodyStyle={{ padding: '0' }}
        width={'75%'}
        // headerStyle={{ display: 'none' }}
        title="书签分类"
        visible={isShowMobile}
        onCancel={changeIsShowMobile}
        placement="left"
        maskStyle={maskStyle}
      >
        <Nav
          style={{ height: '100%', width: '100%' }}
          bodyStyle={{ height: '100%' }}
          defaultOpenKeys={['job', 'resource']}
          items={newBookmark}
          onSelect={(key) => {
            scrollToAnchor(key.selectedItems[0].text);
            changeIsShowMobile();
          }}
          footer={{
            collapseButton: !mediaQuery.matches,
          }}
        />
      </SideSheet>
    </div>
  );
};

// [
//   { itemKey: 'user', text: '用户管理', icon: <IconUser /> },
//   { itemKey: 'union', text: '公会中心', icon: <IconStar /> },
//   {
//     text: '任务平台',
//     icon: <IconSetting />,
//     itemKey: 'job',
//     items: ['任务管理', '用户任务查询'],
//   },
//   {
//     text: '资源管理',
//     icon: <IconFolder />,
//     itemKey: 'resource',
//     items: ['转盘配置', '转盘审核'],
//   },
// ]
